package com.coincalf.admin.web;

import com.coincalf.admin.common.AliyunOSSClientUtil;
import com.coincalf.admin.common.ResultMap;
import com.coincalf.admin.config.ImageConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 上传文件
 * Create Time: 2018年05月19日 15:32
 * C@author lxl
 **/
@Slf4j
@RestController
@RequestMapping("/image")
@Api(value = "图片上传处理", tags = {"图片上传管理"})
public class ImageUpController {
    @Autowired
    private ImageConfig imageConfig;

    @ApiOperation(authorizations = {@Authorization(value = "Authorization")}, value = "阿里云上传服务", httpMethod = "POST")
    @RequestMapping(value = "/AliYunImgUpload", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResultMap aliYunImgUpload(HttpServletRequest request, HttpServletResponse response, @RequestAttribute("file") MultipartFile file) {
        try {
            AliyunOSSClientUtil ossClient = new AliyunOSSClientUtil(
                    imageConfig.getENDPOINT(),
                    imageConfig.getACCESS_KEY_ID(),
                    imageConfig.getACCESS_KEY_SECRET(),
                    imageConfig.getBACKET_NAME(),
                    imageConfig.getFOLDER());
            String name = ossClient.uploadImg2Oss(file);
            String imgUrl = ossClient.getImgUrl(name);
            String[] split = imgUrl.split("\\?");
            String url = split[0];
            log.info("AliYunImgUpload url:" + url);
            response.setContentType("application/json");
            return ResultMap.getSuccessfulResult(url, "图片上传成功");
        } catch (Exception e) {
            response.setContentType("application/json");
            e.printStackTrace();
            log.info("AliYunImgUpload :" + e.getMessage());
            return ResultMap.getFailureResult("上传失败");

        }
    }

    @ApiOperation(authorizations = {@Authorization(value = "Authorization")}, value = "普通上传服务", httpMethod = "POST")
    @RequestMapping(value = "/commonImgUpload", method = RequestMethod.POST)
    @ResponseBody
    public ResultMap commonImgUpload(HttpServletRequest request, @RequestAttribute("file") MultipartFile file) throws IOException {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        // 给新文件拼上时间毫秒，防止重名
        long now = System.currentTimeMillis();
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = imageConfig.COMMON_FILE_URL + "file_" + now + fileExtension;

        log.info("commonImgUpload originalFilename:" + originalFilename);
        log.info("commonImgUpload newUrl:" + url);
        String result = "上传成功";
        try {
            inputStream = file.getInputStream();
            File file1 = new File(url);
            //判断目标文件所在的目录是否存在
            if (!file1.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                log.info("create Fold 目标文件所在目录不存在，准备创建它.");
                if (!file1.getParentFile().mkdirs()) {
                    log.info("create Folder fail");
                }
            }
            file1.createNewFile();
            outputStream = new FileOutputStream(file1);
            byte temp[] = new byte[1024];
            int size = -1;
            while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                outputStream.write(temp, 0, size);
            }
            log.info("File load success.");
        } catch (IOException e) {
            log.warn("File load fail.", e);
            result = "上传失败";
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            return ResultMap.getSuccessfulResult(url, "result");
        }
    }

}
